package com.cloud.wms.base;


import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;

import com.cloud.core.base.BasePresenter;
import com.cloud.core.base.BaseView;
import com.cloud.core.config.ScanConfig;
import com.cloud.core.eventBus.EventBusUtil;
import com.cloud.core.tools.PlayVoiceManager;
import com.cloud.core.tools.VolumeManager;
import com.cloud.core.widget.dialog.LoadingDialog;
import com.cloud.widget.ScanText;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.injection.components.DaggerFragmentComponent;
import com.cloud.wms.injection.components.FragmentComponent;
import com.cloud.wms.injection.modules.FragmentModule;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.dylanc.loadinghelper.LoadingHelper;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.trello.rxlifecycle3.components.support.RxFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;

import static android.app.Activity.RESULT_OK;


/**
 * Created by Tanghaibo
 * 2018/3/23
 * description:Fragment基类 搭配viewpager
 */

public abstract class BaseViewPagerFragment<P extends BasePresenter> extends RxFragment implements BaseView {

    @Inject
    protected P mPresenter;

    protected View mView;

    protected Activity mActivity;

    protected Context mContext;

    private Unbinder unbinder;

    private boolean isVisible = false;

    private LoadingDialog mDialog;

    protected LoadingHelper loadingHelper;

    protected View.OnKeyListener onKeyListenerImp = (v, keyCode, event) -> {
        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
            EditText editText = (EditText) v;
            String result = editText.getText().toString().trim();
            if (!TextUtils.isEmpty(result)) {
                onScanHandle(result, ScanConfig.SCAN_INFRARED_RESULT_CODE);
            }
        }
        return keyCode == KeyEvent.KEYCODE_ENTER;
    };

    @CallSuper
    protected void onScanHandle(String result, int resultCode) {
    }

    @Override
    public void onAttach(Activity activity) {
        mActivity = activity;
        mContext = activity;
        super.onAttach(activity);
    }

    protected FragmentComponent getFragmentComponent() {
        return DaggerFragmentComponent.builder()
                .applicationComponent(FineExApplication.component())
                .fragmentModule(new FragmentModule(this))
                .build();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(getResId(), null);
        setupComponent();
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter.attachView(this);
        unbinder = ButterKnife.bind(this, mView);
        initEvent(savedInstanceState);
        initScanText();
        onVisible();
        if (isUseEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * 初始化扫描框
     */
    private void initScanText() {
        if (getScanText() != null) {
            getScanText().getFocus();
            HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE, HmsScan.CODE128_SCAN_TYPE).create();
            getScanText().setOnScanListener(() -> ScanUtil.startScan(getActivity(), ScanConfig.SCAN_CAMERA_REQUEST_CODE, options));
            getScanText().setOnKeyListener(onKeyListenerImp);
        }
    }

    /**
     * 提供扫描框对象
     *
     * @return
     */
    protected ScanText getScanText() {
        return null;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
        }
    }

    protected void onVisible() {
        if (isVisible && mView != null) {
            initData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
        unbinder = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (isUseEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBusUtil.unregister(this);
        }
    }

    protected boolean isUseEventBus() {
        return false;
    }

    protected abstract int getResId();

    protected abstract void setupComponent();

    protected abstract void initEvent(Bundle bundle);

    protected abstract void initData();

    @Override
    public void onAlert(String content, DialogInterface.OnClickListener listener) {
        new AlertDialogBuilder(this.getContext())
                .setTitle("提示")
                .setMessage(content)
                .setPositiveButton("确定", listener)
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void error(String msg) {
        Toasty.info(this.getContext(), msg).show();
    }

    @Override
    public void info(String msg) {
        Toasty.info(this.getContext(), msg).show();
    }

    @Override
    public void success(String msg) {
        Toasty.success(this.getContext(), msg).show();
    }

    protected LoadingDialog getDialog() {
        if (mDialog == null) {
            mDialog = new LoadingDialog.Builder(mContext).create();
        }
        return mDialog;
    }

    protected void dismiss() {
        if (mDialog == null) {
            return;
        }
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void showLoading() {
        getDialog().show();
    }

    @Override
    public void hideLoading() {
        dismiss();
    }

    @Override
    public void showError() {
        if (loadingHelper != null) {
            loadingHelper.showErrorView();
        }
    }

    @Override
    public void showContent() {
        if (loadingHelper != null) {
            loadingHelper.showContentView();
        }
    }

    @Override
    public void showEmpty() {
        if (loadingHelper != null) {
            loadingHelper.showEmptyView();
        }
    }

    @Override
    public Context provideContext() {
        return mContext;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ScanConfig.SCAN_CAMERA_REQUEST_CODE
                && resultCode == RESULT_OK
                && data != null
                && getScanText() != null) {
            /**
             * 扫码返回的数据（码格式，扫码类型，扫码内容）
             * obj.getOriginalValue();//扫码的结果
             * obj.getScanType();//二维码的格式
             * obj.getScanTypeForm();//二维码内容的类型
             */
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null && !TextUtils.isEmpty(obj.getOriginalValue())) {
                getScanText().setText(obj.getOriginalValue().trim());
                onScanHandle(obj.getOriginalValue().trim(), ScanConfig.SCAN_INFRARED_RESULT_CODE);
            } else {
                info("扫描结果解析失败！");
            }
        }
    }

    public void scanVoice(@RawRes int voice) {
        new VolumeManager(getContext()).setVoice(100);
        PlayVoiceManager.with(getContext()).play(voice);
    }

    public void scanVoice(@RawRes Integer[] voice) {
        new VolumeManager(getContext()).setVoice(100);
        for (int i = 0; i < voice.length; i++) {
            PlayVoiceManager.with(getContext()).play(voice[i]);
        }
    }
}
